package cn.echcz.restboot.controller;

import cn.echcz.restboot.auth.JwtHandler;
import cn.echcz.restboot.constant.ErrorStatus;
import cn.echcz.restboot.exception.HttpClientException;
import cn.echcz.restboot.model.LoginReq;
import cn.echcz.restboot.model.RefreshTokenReq;
import cn.echcz.restboot.model.TokenRing;
import cn.echcz.restboot.model.User;
import cn.echcz.restboot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Api("RootApi")
public class RootApi {
    @NonNull
    private UserService userService;
    @NonNull
    private JwtHandler jwtHandler;

    @ApiOperation("ping")
    @GetMapping("/ping/{name}")
    public String ping(@PathVariable String name) {
        if ("nothing".equals(name)) {
            return null;
        }
        if ("error".equals(name)) {
            throw new RuntimeException();
        }
        return name;
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public TokenRing login(@RequestBody LoginReq loginReq) {
        User user = userService.findByUsername(loginReq.getUsername());
        if (user != null && user.isEnable() && user.getPassword().equals(loginReq.getPassword())) {
            String accessToken = jwtHandler.createAccessTokenByUserId(user.getId());
            String refreshToken = jwtHandler.createRefreshTokenByUserId(user.getId());
            return TokenRing.builder()
                    .accessToken(accessToken)
                    .refreshToken(refreshToken)
                    .build();
        }
        throw new HttpClientException(HttpStatus.UNAUTHORIZED, ErrorStatus.UNAUTHORIZED.getCode(), ErrorStatus.UNAUTHORIZED.getMsg());
    }

    @ApiOperation("刷新token")
    @PostMapping("/refreshToken")
    public TokenRing refreshToken(@RequestBody RefreshTokenReq refreshTokenReq) {
        String token = refreshTokenReq.getToken();
        try {
            if (token != null) {
                Integer userId = jwtHandler.getUserIdFromRefreshToken(token);
                if (userId != null) {
                    String accessToken = jwtHandler.createAccessTokenByUserId(userId);
                    String refreshToken = jwtHandler.createRefreshTokenByUserId(userId);
                    return TokenRing.builder()
                            .accessToken(accessToken)
                            .refreshToken(refreshToken)
                            .build();
                }
            }
        } catch (Exception e) {
            // do nothing
        }
        throw new HttpClientException(HttpStatus.UNAUTHORIZED, ErrorStatus.UNAUTHORIZED.getCode(), ErrorStatus.UNAUTHORIZED.getMsg());
    }
}
